package com.yswee.mallnavi.view.brand.grid;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.yswee.framework.net.ITaskContext;
import com.yswee.framework.utils.StringUtils;
import com.yswee.framework.widget.adapterview.withmodel.MGridView;
import com.yswee.framework.widget.adapterview.withmodel.MListView;
import com.yswee.framework.widget.layoutview.ILayoutView;
import com.yswee.framework.widget.loading.LoadingPullToRefreshGridView;
import com.yswee.mallnavi.R;
import com.yswee.mallnavi.entity.info.BrandEntity;
import com.yswee.mallnavi.model.BaseListModel;
import com.yswee.mallnavi.model.info.BrandListModel;
import com.yswee.mallnavi.view.brand.IGridView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class GridView extends LoadingPullToRefreshGridView<BrandEntity> implements IGridView {
	
	private static final int MSG_WHAT_HIDEOVERLAY = 0;
	private static final int MSG_DELAY_HIDEOVERLAY = 1000;

	private TextView mOverLay;
    private WindowManager mWindowManager; 

	private boolean mShowGroup;
	private String mCategoryId = null;
	private BrandListModel mListModel;
	private HashMap<String, Integer> mAlphaIndexer;

	private IGridView.IActionCallback mActionCallback;

	@Override
	public void setActionCallback(IGridView.IActionCallback c) {
		mActionCallback = c;
	}

	@Override
	public void setFilter(String filter) {
		createMode();
		mListModel.setKeyword(filter);
	}

	@Override
	public void setParams(String categoryId) {
		mCategoryId = categoryId;
		createMode();
		mListModel.setParams(categoryId);
	}

	private Handler mHanlder = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_HIDEOVERLAY:
				mOverLay.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		};
	};
	
	private IGridView.IActionCallback mActionCallbackProxy = new IGridView.IActionCallback() {
		@Override
		public void onBrandClicked(View v, BrandEntity brand) {
			if (mActionCallback != null) {
				mActionCallback.onBrandClicked(v, brand);
			}
		}
	};
	
	public GridView(Context context) {
		super(context);
	}
	
	public GridView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	@Override
	protected boolean hideContentOnAction() {
		return false;
	}

	@Override
	protected void initializeGridView(MGridView<BrandEntity> gridview) {
		super.initializeGridView(gridview);
		gridview.setHorizontalScrollBarEnabled(false);
		gridview.setVerticalScrollBarEnabled(false);
		int space_h = (int) getResources().getDimension(R.dimen.gridview_h_spacing);
		int space_v = (int) getResources().getDimension(R.dimen.gridview_v_spacing);
		gridview.setNumColumns(3);
		gridview.setStretchMode(android.widget.GridView.STRETCH_COLUMN_WIDTH);
		gridview.setHorizontalSpacing(space_h);
		gridview.setVerticalSpacing(space_v);
		gridview.setSelector(R.drawable.gridview_selector);
		if (mShowGroup) {
			initOverlay();
		}
	}

	@Override
	protected BaseListModel<BrandEntity> createMode() {
		if (mListModel == null) {
			ITaskContext context = mContext instanceof ITaskContext ?
					(ITaskContext) mContext : null;
			mListModel = new BrandListModel(context);
		}
		return mListModel;
	}

	@Override
	protected boolean isReadyLoadData(boolean isFirstPage) {
		return mCategoryId != null;
	}

	@Override
	protected boolean enabledLoadNextPage() {
		return false;
	}
	
	@Override
	protected int getViewTypeCount() {
		return BrandEntity.VIEWTYPECOUNT;
	}
	
	@Override
	protected int getListViewType() {
		return MListView.LISTVIEW_TYPE_VIEW;
	}
	
	@Override
	protected ILayoutView<BrandEntity> getLayoutView(int position, BrandEntity t, int itemViewType) {
		if(itemViewType == BrandEntity.VIEWTYPEGROUP) {
			return null;
		} else {
			GridItem griditem = new GridItem(mContext);
			griditem.setActionCallback(mActionCallbackProxy);
			return griditem;
		}
	}

	@Override
	protected ArrayList<BrandEntity> transferDataSource(ArrayList<BrandEntity> array) {
		if (array == null) {
			return array;
		}
		if (mListModel.getDataArray() != null) {
			ArrayList<BrandEntity> data = mListModel.getDataArray();
			array.clear();
			Collections.sort(data);
			String prevAlpla = null;
			for (int i = 0; i < data.size(); i++) {
				if (mShowGroup) {
					String alpha = data.get(i).key;
					if(!TextUtils.isEmpty(alpha) && !alpha.equals(prevAlpla)) {
						BrandEntity contact = new BrandEntity();
						contact.name = null;
						contact.key = alpha;
						contact.isGroup = true;
						array.add(contact);
						prevAlpla = alpha;
					}
				}
				array.add(data.get(i));
			}
			setOverLayDataSource(array);
		}
		return array;
	}

	@Override
	public void onDestroy() {
		if(mWindowManager != null) {
			if(mOverLay != null) {
				mWindowManager.removeView(mOverLay);
				mOverLay = null;
			}
		}
	}

	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(getContext());
		mOverLay = (TextView) inflater.inflate(R.layout.widget_letter_overlay, null);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(120,
				120, 0, 0, WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		mWindowManager = (WindowManager) getContext()
				.getSystemService(Context.WINDOW_SERVICE);
		mWindowManager.addView(mOverLay, lp);
	}

	private void setOverLayDataSource(ArrayList<BrandEntity> data) {
		mAlphaIndexer = new HashMap<String, Integer>();
		if(data != null) {
			if(mShowGroup) {
				for(int i = 0; i < data.size(); i++) {
					if(data.get(i).isGroup) {
						mAlphaIndexer.put(data.get(i).key, i);
					}
				}
			} else {
				String prevAlpla = null;
				for(int i = 0; i < data.size(); i++) {
					String alpha = data.get(i).key;
					if(!TextUtils.isEmpty(alpha) && !alpha.equals(prevAlpla)) {
						mAlphaIndexer.put(alpha, i);
						prevAlpla = alpha;
					}
				}
			}
		}
	}

	@Override
	public void setSelectionKey(String key) {
		if(mAlphaIndexer == null)
			return;
		if(mListView.getRefreshableView().getDataSource() == null)
			return;
		if (mAlphaIndexer.get(key) == null) {
			String[] groups = StringUtils.getGroupKeys();
			for(int i = 0; i < groups.length; i++) {
				if(groups[i].equals(key)) {
					for(int j = i + 1; j < groups.length; j++) {
						if(mAlphaIndexer.get(groups[j]) != null) {
							mAlphaIndexer.put(key, mAlphaIndexer.get(groups[j]));
							break;
						}
					}
					if(mAlphaIndexer.get(key) == null) {
						mAlphaIndexer.put(key, mListView.getRefreshableView().getDataSource().size() - 1);
					}
					break;
				}
			}
		}
		if(mAlphaIndexer.get(key) != null) {
			mListView.getRefreshableView().setSelection(mAlphaIndexer.get(key));
			if (mShowGroup) {
				mOverLay.setText(key);
				mOverLay.setVisibility(View.VISIBLE);
				mHanlder.removeMessages(MSG_WHAT_HIDEOVERLAY);
				mHanlder.sendEmptyMessageDelayed(MSG_WHAT_HIDEOVERLAY, MSG_DELAY_HIDEOVERLAY);
			}
		}
	}
	
}